package com.heavenick.app.jmx;

import java.util.HashMap;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.remote.JMXAuthenticator;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import javax.security.auth.Subject;

/**
 * 
 * @author HaiJun
 * @date 2013-2-4
 */
public class RMIAdaptAgent {
	
	public static void main(String[] args) throws Exception {        
		MBeanServer server = MBeanServerFactory.createMBeanServer("test1");
		ObjectName helloName = new ObjectName("chengang:name=HelloWorld");        
		Hello hello=new Hello();
		server.registerMBean(hello, helloName);
		hello.addNotificationListener(new HelloAgent(), null, null);
		
		ObjectName adapterName = new ObjectName("HelloAgent:name=rmiadapter"); 
		JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://127.0.0.1:5000/jndi/rmi/test");
		
//		RMIConnectorServer  connector = new RMIConnectorServer(url,null);\
        HashMap<String, Object> prop = new HashMap<String, Object>();    
        prop.put(JMXConnectorServer.AUTHENTICATOR, new JMXAuthenticator() {    
    
            public Subject authenticate(Object credentials) {    
                System.out.println(credentials);    
                if (credentials instanceof String) {    
                    if (credentials.equals("hello")) {    
                        return new Subject();    
                    }    
                }    
                throw new SecurityException("not authicated");    
            }    
        });    
		JMXConnectorServer connectorServer= 
				JMXConnectorServerFactory.newJMXConnectorServer(url, prop, server);
		server.registerMBean(connectorServer, adapterName);
		connectorServer.start();
		System.out.println("start.....");    
		
		
		ObjectInstance object = server.getObjectInstance(helloName);
		System.out.println();
		
		for(;;){
			Hello obj = (Hello)server.instantiate(object.getClassName());
			System.out.println(obj.getName()+" test new Hello for MBean server " + server.getAttribute(helloName, "Name"));
			try {
				Thread.sleep(3000L);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}

}
